package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;

public class LongestCommonPrefix {

    /**
     * 直接循环比较，不需要比较end后面的字符，可以减少比较次数
     *
     * @param strs
     *  0 <= strs.length <= 200
     *  0 <= strs[i].length <= 200
     *  strs[i] 仅由小写英文字母组成
     */
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0){
            return "";
        }
        String s = strs[0];
        int end = s.length();
        for (int i = 1; i < strs.length && end > 0; ++i){
            String str = strs[i];
            if (end > str.length()){
                end = str.length();
            }
            int j = 0;
            while (j < end && str.charAt(j) == s.charAt(j)){
                j++;
            }
            if (j < end){
                end = j;
            }
        }
        if (end == 0){
            return "";
        }
        return s.substring(0, end);
    }

    public static void main(String[] args) {
//        String[] strs = new String[]{"flower","flow","flight"};
        String[] strs = new String[]{"cir","car"};
        String s = new LongestCommonPrefix().longestCommonPrefix(strs);
        Assert.isTrue(s.equals("c"));
    }

}
